package dao

import (
	"RedWork/model"
	"RedWork/util"
	"fmt"
	"log"
)

type HotRes struct {
	GoodID   int     `json:"good_id"`
	GoodName string  `json:"good_name"`
	Image    string  `json:"image"`
	Price    float64 `json:"price"`
	HeadTag  string  `json:"head_tag"`
	FootTag  string  `json:"foot_tag"`
	StoreID  int     `json:"store_id"`
	Brand    string  `json:"brand"`
}

func GetStoreGoods(sid string) (data []model.PhoneInfo) {
	sqlStr := "select * from phone_info where store_id = ?"
	//sqlStr := fmt.Sprintf("select good_id, good_name, price, store_id, store_name, category, good_image,introduce from good_info where store_id = %s", sid)
	rows, err := DB.Query(sqlStr, sid)
	defer rows.Close()
	if err != nil {
		if ok, _, _ := util.ErrHandle(err); ok {
			fmt.Println("mysql err")
		}
	}
	phones := make([]model.PhoneInfo, 0)
	fmt.Println("rows=", rows)
	if rows != nil {
		fmt.Println("Enter?")
		for rows.Next() {
			var phone_data model.PhoneInfo
			err := rows.Scan(
				&phone_data.GoodID,
				&phone_data.GoodName,
				&phone_data.GoodImage,
				&phone_data.Brand,
				&phone_data.ScreenSize,
				&phone_data.ChargingPower,
				&phone_data.IPV6,
				&phone_data.Turnover,
				&phone_data.CommentNum,
				&phone_data.CreateTime,
				&phone_data.Price,
				&phone_data.StoreID,
			)
			fmt.Println(phone_data)
			if err != nil {
				if ok, _, _ := util.ErrHandle(err); ok {
					fmt.Println("mysql err")
				}
				break
			}
			phones = append(phones, phone_data)
			//fmt.Println(goods)
		}
	}

	if len(phones) == 0 {
		return nil
	}
	//bytes, _ := json.Marshal(phones)
	//fmt.Println(string(bytes))
	return phones
}

func QueryStoreHead(sid string) (res []HotRes) {
	sqlStr := "select good_id, name, image, price, head_tag, " +
		"foot_tag, store_id, brand from xiaomi where store_id = ?"
	rows, err := DB.Query(sqlStr, sid)
	defer rows.Close()
	if err != nil {
		log.Println(err)
		return
	}
	for rows.Next() {
		var temp HotRes
		err = rows.Scan(
			&temp.GoodID,
			&temp.GoodName,
			&temp.Image,
			&temp.Price,
			&temp.HeadTag,
			&temp.FootTag,
			&temp.StoreID,
			&temp.Brand,
		)
		if err != nil {
			log.Println(err)
			return nil
		}
		if temp.GoodID != 0 {
			res = append(res, temp)
		}
	}
	return
}
